package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.Result;
import com.docmgmt.mvp.ragflow.KnowledgeBaseData;
import com.docmgmt.mvp.ragflow.RAGFlowClient;
import com.docmgmt.mvp.ragflow.dto.KnowledgeBaseDetailVO;
import com.docmgmt.mvp.ragflow.dto.UpdateKnowledgeBaseRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Map;

/**
 * RAGFlow 知识库管理 Controller
 * 
 * 提供知识库的CRUD操作API
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/ragflow/datasets")
@RequiredArgsConstructor
@Validated
@Tag(name = "RAGFlow知识库管理", description = "RAGFlow知识库配置管理接口")
public class RAGFlowDatasetController {

    private final RAGFlowClient ragflowClient;

    /**
     * 列出所有知识库
     *
     * GET /api/v1/ragflow/datasets
     */
    @GetMapping
    @PreAuthorize("hasAuthority('ragflow:kb:read')")
    @Operation(summary = "列出所有知识库", description = "获取所有知识库列表")
    public Result<List<KnowledgeBaseData>> listKnowledgeBases() {

        log.info("列出所有知识库");

        try {
            List<KnowledgeBaseData> knowledgeBases = ragflowClient.listKnowledgeBases();
            return Result.success(knowledgeBases);
        } catch (Exception e) {
            log.error("列出知识库失败", e);
            return Result.error("列出知识库失败: " + e.getMessage());
        }
    }

    /**
     * 获取知识库详情
     *
     * GET /api/v1/ragflow/datasets/{datasetId}
     */
    @GetMapping("/{datasetId}")
    @PreAuthorize("hasAuthority('ragflow:kb:read')")
    @Operation(summary = "获取知识库详情", description = "获取指定知识库的完整配置信息")
    public Result<KnowledgeBaseDetailVO> getKnowledgeBaseDetail(
            @Parameter(description = "知识库ID", required = true)
            @PathVariable String datasetId) {

        log.info("获取知识库详情: datasetId={}", datasetId);

        try {
            KnowledgeBaseDetailVO detail = ragflowClient.getKnowledgeBaseDetail(datasetId);
            return Result.success(detail);
        } catch (Exception e) {
            log.error("获取知识库详情失败: datasetId={}", datasetId, e);
            return Result.error("获取知识库详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新知识库配置
     * 
     * PUT /api/v1/ragflow/datasets/{datasetId}
     */
    @PutMapping("/{datasetId}")
    @PreAuthorize("hasAuthority('ragflow:kb:update')")
    @Operation(summary = "更新知识库配置", description = "更新知识库的名称、描述、分块方法、解析器配置等")
    public Result<KnowledgeBaseDetailVO> updateKnowledgeBase(
            @Parameter(description = "知识库ID", required = true)
            @PathVariable String datasetId,
            
            @Parameter(description = "更新请求", required = true)
            @Valid @RequestBody UpdateKnowledgeBaseRequest request) {
        
        log.info("更新知识库配置: datasetId={}, name={}", datasetId, request.getName());
        
        try {
            KnowledgeBaseDetailVO updated = ragflowClient.updateKnowledgeBase(datasetId, request);
            return Result.success(updated);
        } catch (Exception e) {
            log.error("更新知识库配置失败: datasetId={}", datasetId, e);
            return Result.error("更新知识库配置失败: " + e.getMessage());
        }
    }

    /**
     * 删除知识库
     * 
     * DELETE /api/v1/ragflow/datasets
     * Body: {"ids": ["kb_id_1", "kb_id_2"]}
     */
    @DeleteMapping
    @PreAuthorize("hasAuthority('ragflow:kb:delete')")
    @Operation(summary = "删除知识库", description = "批量删除知识库（会级联删除所有文档和chunks）")
    public Result<Void> deleteKnowledgeBases(
            @Parameter(description = "知识库ID列表", required = true)
            @Valid @RequestBody Map<String, List<String>> requestBody) {
        
        List<String> ids = requestBody.get("ids");
        
        if (ids == null || ids.isEmpty()) {
            return Result.error("ids参数不能为空");
        }
        
        log.info("删除知识库: ids={}", ids);
        
        try {
            ragflowClient.deleteKnowledgeBases(ids);
            return Result.success("知识库删除成功");
        } catch (Exception e) {
            log.error("删除知识库失败: ids={}", ids, e);
            return Result.error("删除知识库失败: " + e.getMessage());
        }
    }
}

